package com.TaskOrganizer.actions;

import java.awt.event.ActionEvent;
import java.io.File;

import javax.swing.Action;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;

import com.TaskOrganizer.core.AppCore;

public class Backup extends DefaultAction {
	private static final long serialVersionUID = 6582080630810693727L;

	public Backup() {
		super();
		putValue(Action.NAME, "Backup Tasks");
		putValue(Action.SMALL_ICON, getIcon("/com/TaskOrganizer/icons/"
				+ getValue(Action.NAME).toString().toLowerCase() + ".png"));
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		while (true) {
			File file = new File(AppCore.getInstance().getStorePath()
					+ "TaskOrganizer\\backup");
			file.mkdirs();

			JFileChooser jfc = new JFileChooser(AppCore.getInstance()
					.getStorePath() + "TaskOrganizer\\backup");
			jfc.setMultiSelectionEnabled(false);
			jfc.setAcceptAllFileFilterUsed(false);
			jfc.setFileFilter(new FileFilter() {

				@Override
				public String getDescription() {
					return "TaskOrganizer - .tsk";
				}

				@Override
				public boolean accept(File arg0) {
					if (arg0.getName().endsWith(".tsk") || arg0.isDirectory())
						return true;
					return false;
				}
			});
			int option = jfc.showSaveDialog(null);
			if (option == JFileChooser.APPROVE_OPTION) {
				file = jfc.getSelectedFile();
				if (!file.getName().endsWith(".tsk")) {
					file = new File(file.getAbsolutePath() + ".tsk");
				}
				if (file.exists()) {
					option = JOptionPane.showConfirmDialog(null,
							"Do you wish to owerwrite the file?");
					if (option == JOptionPane.OK_OPTION) {
						AppCore.getInstance().saveTaskList(file);
						return;
					}
					if (option == JOptionPane.NO_OPTION) {
						return;
					}
				} else {
					AppCore.getInstance().saveTaskList(file);
					return;
				}

			} else {
				return;
			}
		}
	}
}
